<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="searchOptions.yearmonth"
        type="month"
        placeholder="选择月份"
        class="filter-item"
      />
      <el-select v-model="searchOptions.failureType" placeholder="故障类型" clearable style="width: 130px" class="filter-item">
        <el-option v-for="item in failureTypeOptions" :key="item" :label="item" :value="item" />
      </el-select>

      <el-select v-model="searchOptions.orderProcess" placeholder="订单进度" clearable class="filter-item" style="width: 120px">
        <el-option v-for="item in orderProcessOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-input v-model="searchOptions.staffId" placeholder="师傅工号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <!-- <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button> -->

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <!-- {{ searchOptions }} -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      stripe
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column show-overflow-tooltip label="订单号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>

      <el-table-column label="报修地址" align="center">
        <template slot-scope="{row}">
          <div>{{ row.region.split(',')[0] }}</div>
          <div>{{ row.region.split(',')[1] }}</div>

        </template>
      </el-table-column>

      <el-table-column label="故障类型" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.failureType=='网速太慢'" color="#FFF0F6" style="color: rgba(0, 0, 0,0.5);border: none;">
            网速太慢
          </el-tag>
          <el-tag v-else-if="row.failureType=='无法上网'" color="#FFF2E8" style="color: rgba(0, 0, 0,0.5);border: none;">
            无法上网
          </el-tag>
          <el-tag v-else color="#E6FFFB" style="color: rgba(0, 0, 0, 0.5);border: none;">
            其他原因
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="订单进度" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.orderProcess==0" color="#eebe77" style="color: rgb(255, 255, 255);border: none;">
            待处理
          </el-tag>
          <el-tag v-else-if="row.orderProcess==1" color="#95d475" style="color: rgb(255, 255, 255);border: none;">
            处理中
          </el-tag>
          <el-tag v-else-if="row.orderProcess==2" color="#79bbff" style="color: rgb(255, 255, 255);border: none;">
            已完成
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="接单师傅" align="center">
        <template slot-scope="{row}">
          <div v-if="(row.hasOwnProperty('staffId'))">

            <div>{{ row.employeeIdName.slice(0,6) }}</div>
            <div>{{ row.employeeIdName.slice(6) }}</div>

          </div>
          <span v-else-if="!(row.hasOwnProperty('staffId'))">暂无</span>
        </template>
      </el-table-column>

      <el-table-column label="报修时间" width="120" align="center">
        <template slot-scope="{row}">
          <div>{{ row.orderTime.split(' ')[0] }}</div>
          <div>{{ row.orderTime.split(' ')[1] }}</div>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="success" @click="handleInfo(row,$index)">
            详情
          </el-button>
          <!-- <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <!-- {{ total }} {{ listQuery }} -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="订单进度" prop="orderProcess">
          <el-select v-model="temp.orderProcess" class="filter-item" placeholder="修改订单进度" @change="setRules">
            <el-option v-for="item in orderProcessOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="维修师傅" prop="employeeIdName">
          <el-select v-model="temp.employeeIdName" :disabled="temp.orderProcess==='待处理'" class="filter-item" placeholder="更换维修师傅">
            <el-option v-for="item in employeeIdNameOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <!-- {{ temp }} -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="infoTitle" :visible.sync="dialogINFOFormVisible">

      <el-descriptions
        :column="2"
        :title="'维修单号 '+temp.orderId"
        size="large"
      >

        <el-descriptions-item label="申请人">{{ temp.nickName }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ temp.tel }}</el-descriptions-item>
        <el-descriptions-item label="报修区域">{{ temp.region }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{ temp.addr }}</el-descriptions-item>
        <el-descriptions-item label="报修方式">{{ temp.orderType }}</el-descriptions-item>
        <el-descriptions-item label="报修时间">{{ temp.orderTime }}</el-descriptions-item>
        <el-descriptions-item label="催单次数">{{ temp.urgedCount }}</el-descriptions-item>
        <el-descriptions-item label="催单时间">{{ temp.urgedTime }}</el-descriptions-item>
        <el-descriptions-item label="用户学号">{{ temp.stuId }}</el-descriptions-item>

        <el-descriptions-item label="订单进度">
          <el-tag v-if="temp.orderProcess==0" size="small" color="#eebe77" style="color: rgb(255, 255, 255);border: none;">
            待处理
          </el-tag>
          <el-tag v-else-if="temp.orderProcess==1" size="small" color="#95d475" style="color: rgb(255, 255, 255);border: none;">
            处理中
          </el-tag>
          <el-tag v-else-if="temp.orderProcess==2" size="small" color="#79bbff" style="color: rgb(255, 255, 255);border: none;">
            已完成
          </el-tag>
        </el-descriptions-item>

      </el-descriptions>
      <div style="margin-top: 10px;" />
      <el-descriptions
        :column="2"
        title="故障信息"
        size="large"
      >
        <el-descriptions-item label="故障类型">{{ temp.failureType }}</el-descriptions-item>
        <el-descriptions-item label="故障详情">{{ temp.failureDetail }}</el-descriptions-item>
        <el-descriptions-item label="故障图片">

          <el-image
            style="width: 100px; height: 100px"
            :src="temp.filePath"
            fit="cover"
            :preview-src-list="[temp.filePath]"
            :initial-index="0"
          />

        </el-descriptions-item>
      </el-descriptions>
      <div style="margin-top: 10px;" />
      <el-descriptions
        :column="2"
        title="技术员信息"
        size="large"
      >
        <el-descriptions-item label="技术员姓名">{{ temp.employeeInfo.employeeName }}</el-descriptions-item>
        <el-descriptions-item label="工号">{{ temp.employeeInfo.staffId }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ temp.employeeInfo.staffTel }}</el-descriptions-item>

      </el-descriptions>

      <div style="margin-top: 10px;" />
      <el-descriptions
        :column="2"
        title="完成信息"
        size="large"
      >
        <el-descriptions-item label="完成时间">{{ temp.completeTime }}</el-descriptions-item>
        <el-descriptions-item label="解决方案" />
        <el-descriptions-item label="完成图片">
          <el-image
            v-if="temp.completedFilePath !=null"
            style="width: 100px; height: 100px"
            :src="temp.completedFilePath"
            fit="cover"
            :preview-src-list="[temp.completeFilePath]"
            :initial-index="0"
          />
        </el-descriptions-item>

      </el-descriptions>
    </el-dialog>

  </div>
</template>

<script>
import { fetchOrder, fetchEmployeee, updateOrder } from '@/api/order'
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// function compare(property, property2) {
//   return function(a, b) {
//     var value1 = a[property]
//     var value2 = b[property]
//     if (value1 !== value2) {
//       return value1 - value2
//     }
//     return a[property2] - b[property2]
//   }
// }

export default {
  name: 'Ordermanager',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      employeeIdNameOptions: [],
      employeeData: [],
      infoTitle: '详情',
      times: ['1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '24:00'],
      ori_data: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      searchOptions: {
        yearmonth: '',
        failureType: '',
        orderProcess: '',
        staffId: ''
      },
      dormitoryOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
      failureTypeOptions: ['网速太慢', '无法上网', '其他原因'],
      orderProcessOptions: ['待处理', '处理中', '已完成'],
      showReviewer: false,
      temp: {
        createTime: '',
        deleted: '',
        id: '',
        nickName: '',
        orderId: '',
        orderProcess: '',
        orderTime: '',
        staffId: '',
        stuId: '',
        tel: '',
        updateTime: '',
        urgedCount: '',
        userName: '',
        employeeIdName: '',
        employeeInfo: { nickName: '', staffId: '', staffTel: '' }
      },
      dialogFormVisible: false,
      dialogINFOFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        info: '详情'
      },
      downloadLoading: false,
      rules: {
        orderProcess: [{ required: true, message: '必填', trigger: 'change' }],
        employeeIdName: [{ required: false, message: '请选择师傅', trigger: 'change' }]
      }
    }
  },
  created() {
    const staffId = this.$route.query.staffId
    if (staffId) {
      // console.log(staffId)
      this.searchOptions.staffId = staffId
    }
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchEmployeee().then(response => {
        var EmployeeList = response.data.data
        // console.log('EmployeeList', EmployeeList)
        var newlist = []
        EmployeeList.forEach(element => {
          if (element.staffId === undefined && element.nickName === undefined) {
            return
          }
          var text = element.staffId + element.nickName
          newlist.push(text)
        })
        newlist.sort()
        this.employeeData = EmployeeList
        this.employeeIdNameOptions = newlist
      })

      fetchOrder(this.listQuery).then(response => {
        const orderInfo = response.data.data

        this.ori_data = orderInfo.records

        this.list = this.ori_data
        this.list.forEach(element => {
          if (element.staffId !== '') {
            element.employeeIdName = this.employeeIdNameOptions.filter(item => {
              return item.slice(0, 6).indexOf(element.staffId) !== -1
            })
            element.employeeIdName = element.employeeIdName[0]
          } else {
            element.employeeIdName = ''
          }
        })

        this.alltotal = orderInfo.total
        this.total = orderInfo.total

        if (this.searchOptions.staffId !== '') {
          this.handleFilter()
        }

        setTimeout(() => {
          this.listLoading = false
        }, 0.6 * 1000)
      })
    },
    handleFilter() {
      // const dorm_num = this.searchOptions.dorm_num
      const yearmonth = this.searchOptions.yearmonth
      const failureType = this.searchOptions.failureType
      var orderProcess = this.searchOptions.orderProcess
      var staffId = this.searchOptions.staffId

      // console.log(yearmonth)
      var date = new Date(yearmonth)
      // console.log(date)
      // console.log(date.getFullYear(), date.getMonth())
      let result = this.ori_data
      const year = date.getFullYear()
      const month = date.getMonth()

      if (yearmonth !== '') {
        result = result.filter(item => {
          var itemdate = new Date(item.createTime)
          const itemyear = itemdate.getFullYear()
          const itemmonth = itemdate.getMonth()

          // console.log(itemyear, itemmonth)

          return itemyear === year && itemmonth === month
        })
      } else if (failureType !== '') {
        result = result.filter(item => {
          if (failureType === '其他原因') {
            var text = ''

            this.failureTypeOptions.forEach(i => {
              if (i === '其他原因') {
                return
              }
              text = text + `item.failureType !== '${i}' && `
            })

            text = text.slice(0, -3)
            var fun = new Function('item', 'return ' + text)
            return fun(item)
          } else {
            return item.failureType === failureType
          }
        })
      } else if (orderProcess !== '') {
        if (orderProcess === '待处理') {
          orderProcess = 0
        } else if (orderProcess === '处理中') {
          orderProcess = 1
        } else if (orderProcess === '已完成') {
          orderProcess = 2
        }
        result = result.filter(item => {
          return item.orderProcess === orderProcess
        })
      } else if (staffId !== '') {
        result = result.filter(item => {
          return item.staffId === staffId
        })
      }

      this.list = result
      this.total = result.length
      if (staffId === '' && orderProcess === '' && failureType === '' && yearmonth === '') {
        this.list = this.ori_data
        this.total = this.alltotal
      }

      // console.log(result)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        createTime: '',
        deleted: '',
        id: '',
        nickName: '',
        orderId: '',
        orderProcess: '',
        orderTime: '',
        staffId: '',
        stuId: '',
        tel: '',
        updateTime: '',
        urgedCount: '',
        userName: '',
        employeeIdName: '',
        employeeInfo: { nickName: '', staffId: '', staffTel: '' }

      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleInfo(row, index) {
      this.resetTemp()
      this.dialogINFOFormVisible = true

      this.temp = row
      this.temp.employeeInfo = {}
      this.temp.employeeInfo.staffId = row.staffId
      var a = this.employeeData.filter(item => {
        // console.log(item.staffId, typeof row.staffId)
        // console.log(row.staffId, typeof row.staffId)
        // console.log(item.staffId === row.staffId)
        return item.staffId === row.staffId
      })
      // console.log('a', a)

      this.temp.employeeInfo.employeeName = a[0].nickName
      this.temp.employeeInfo.staffTel = a[0].tel

      // console.log('this.employeeData', this.employeeData)

      // this.temp.employeeInfo.employeeName = this.employeeData.filter(item => {
      //   return item.staffId === row.staffId
      // }).nickName
    },
    handleUpdate(row) {
      this.resetTemp()

      this.temp = { ...this.temp, ...row }
      this.temp.orderId = row.orderId
      this.temp.employeeIdName = ''
      this.temp.orderProcess = this.orderProcessOptions[row.orderProcess]

      // this.temp.employeeIdName = '1122'

      if (row.staffId !== '') {
        this.temp.employeeIdName = this.employeeIdNameOptions.filter(item => {
          // console.log('item', item, typeof item)
          // console.log('row.staffId', row.staffId)
          return item.slice(0, 6).indexOf(row.staffId) !== -1
        })
        this.temp.employeeIdName = this.temp.employeeIdName[0]
      } else {
        this.temp.employeeIdName = ''
      }

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        // console.log(valid)
        if (valid) {
          const tempData = Object.assign({}, this.temp)

          var a = this.orderProcessOptions.findIndex(item => {
            return item === tempData.orderProcess
          })

          tempData.orderProcess = a
          console.log(tempData)

          const data = {
            orderId: tempData.orderId,
            orderProcess: String(tempData.orderProcess)
          }

          if (tempData.employeeIdName !== undefined) {
            tempData.staffId = tempData.employeeIdName.slice(0, 6) || ''
            data.staffId = tempData.staffId
          }

          updateOrder(data).then(() => {
            console.log('update')
            const index = this.list.findIndex(v => v.orderId === tempData.orderId)
            this.list.splice(index, 1, tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
          })

          // location.reload()
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    // handleFetchPv(pv) {
    //   fetchPv(pv).then(response => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单号', '申请人', '手机号', '报修地址', '故障类型', '订单进度', '师傅ID', '报修时间', '创建时间']
        const filterVal = ['orderId', 'nickName', 'tel', 'detail.addr', 'detail.failureType', 'orderProcess', 'staffId', 'orderTimeDate', 'createdAt']
        const data = this.formatJson(filterVal)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-orders'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j.split('.')[0] === 'detail') {
            // console.log(v['detail'][j.split('.')[1]])
            return v['detail'][j.split('.')[1]]
          } else {
            // console.log(v[j])
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    setRules(e) {
      console.log(e)
      console.log(this.rules)
      if (e === '待处理') {
        this.rules.employeeIdName[0].required = false
      }
    }
  }}

</script>
